<template>
  <div class="c-ph24" v-if="isShowInvite">
    <div class="c-mt20 c-br10 c-bg-sgray c-w100 c-pv36 c-ph64 c-fs24 c-lh32 c-fc-sxblack">您好！
      <span class="c-fc-smblue">{{mpName}}</span> 邀请您成为{{questionCustom == 1 ? '预约区的光之管道' : '问答区的答主'}}， 完善资料即可！
    </div>
    <div class="c-bd-b1 c-fs24 c-pt48 c-pb20">
      <input v-model="userName" class="c-w100" type="text" maxlength ="10" placeholder="请输入真实姓名">
    </div>
    <div class="c-bd-b1 c-fs24 c-pt66 c-pb20">
      <input v-model="userPhone" class="c-w100" type="tel" maxlength ="11" placeholder="请输入手机号码" @input = "userPhone=userPhone.replace(/[^\d]/g,'')">
    </div>
    <div class="c-bd-b1 c-fs24 c-pt66 c-pb20 c-flex-row c-aligni-center">
      <input v-model="imgCode" type="text" placeholder="请输入验证码" maxlength ="4" @input = "imgCode=imgCode.replace(/[^\w]/g,'')">
      <span class="c-fc-gray c-ph24">|</span>
      <div class="c-flex-grow1 c-w0 c-flex-row c-flex-center">
        <img :src="$addXossFilter(codeImgInfo.img)" @click="getImgCode" class="c-ww130" alt="">
      </div>
    </div>
    <div class="c-bd-b1 c-fs24 c-pt66 c-pb20 c-flex-row c-aligni-center">
      <input v-model="vCode" type="text" placeholder="请输入验证码" maxlength ="6" @input="vCode=vCode.slice(0, 4);vCode=vCode.replace(/[^\w]/g,'')">
      <span class="c-fc-gray c-ph24">|</span>
      <span v-if="vCodeTime == 60" @click="getVCode" class="c-flex-grow1 c-w0 c-textAlign-c">获取验证码</span>
      <span v-else class="c-flex-grow1 c-w0 c-textAlign-c">{{vCodeTime}}秒后重新获取</span>
    </div>
    <div class="c-pt32 c-fs24 c-pb20">真实头像</div>
    <div class="c-p c-inlineblack" v-show="headUrl">
      <div @click="delUploadImage" class="upload-img-del">x</div>
      <img class="c-ww150 c-hh150" @click="clickPreviewImage" :src="$addXossFilter(headUrl)" alt="" />
    </div>

    <div v-show="!headUrl" class="c-ww150 c-hh150 c-p">
      <div class="c-ww150 c-hh150 c-bg-sgray c-flex-row c-flex-center" @click="clickChoosePic">
        <span class="c-fs100 c-fc-sgray">+</span>
      </div>
      <input class="c-pa c-opacity0 c-p-t0 c-p-l0 c-ww150 c-hh150 c-fs10" v-if="!isWeiXin" ref="uploadImg" name="file" type="file" accept="image/*" @change="clickChoosePic($event)" />
    </div>

    <div v-if="questionCustom == 1" class="c-fs24">
      <div class="c-ws-n c-ww130 c-pv20">光之管道等级</div>
      <div class="c-bd1-mgray c-br10 modal-textarea">
        <textarea v-model="honor" placeholder='请如实填写您的光之管道等级，如:"灵魂唤醒师"'></textarea>
      </div>
      <div class="c-ws-n c-ww130 c-pv20">光之管道简介</div>
      <div class="c-bd1-mgray c-br10 modal-textarea">
        <textarea v-model="intro" placeholder="请填写您的个人简介" maxlength="200"></textarea>
        <div class="c-textAlign-r c-fc-gray">{{intro.length}}/200</div>
      </div>
      <div class="c-ws-n c-ww130 c-pv20">收费价格</div>
      <input type="number" v-model="price" class="c-w100 price">
    </div>
    <div class="c-fs24" v-else>
      <div class="c-pt32 c-pb20">职位头衔(选填)</div>
      <div class="c-bd1-mgray c-br10 modal-textarea">
        <textarea v-model="honor" placeholder="请输入职位头衔" maxlength="50"></textarea>
        <div class="c-textAlign-r c-fc-gray">{{honor.length}}/50</div>
      </div>
    </div>
    <div class="c-fs24">
      <div class="c-pt32 c-pb20">备注(选填)</div>
      <div class="c-bd1-mgray c-br10 modal-textarea">
        <textarea v-model="remark" placeholder="请输入备注" maxlength="200"></textarea>
        <div class="c-textAlign-r c-fc-gray">{{remark.length}}/200</div>
      </div>
    </div>
    <div @click="clickAccessInvite" class="c-bd1 c-mt40 c-br6 c-fs28 c-w100 c-pv20 c-textAlign-c theme-bg c-fc-white">接受邀请</div>

  </div>
</template>

<script>
import { utilJs, wxUtilJs } from "@/utils/common.js";
let isClicking = false;
let vCodeTimeCon;
let imgData = {};
export default {
  name: "InviteLord",
  components: {},
  props: [],
  beforeCreate() { },
  data() {
    return {
      theme: localStorage.getItem("colorName")
        ? localStorage.getItem("colorName")
        : "mb5_default",
      userName: "",
      mpName: localStorage.getItem("companyName"),
      questionCustom: localStorage.getItem("questionCustom"), //定制阿卡西线上学院
      questionInfo: JSON.parse(localStorage.getItem("questionInfo")),
      userPhone: "",
      vCode: "",
      vCodeTime: 60,
      headUrl: "",
      codeImgInfo: '', //图形验证码信息
      imgCode: '', //填入的图形验证码
      isWeiXin: true,
      lecturerId: '', // 讲师id
      honor: "", //等级
      intro: "", //简介
      price: "", //收费价格
      remark: "", //备注
      isShowInvite: false,
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() { },
  computed: {},
  watch: {},
  methods: {
    getImgCode() {
      let $this = this;
      if ($this.isLoading == true) {
        return;
      }
      $this.isLoading = true;
      utilJs.getMethod(`${global.apiurl}common/captcha`, res => {
        $this.codeImgInfo = res;
        $this.isLoading = false;
      }, failRes => {
        $this.isLoading = false;
      });
    },
    //获取自己的答主信息
    getSelfAnswerInfo() {
      utilJs.getMethod(global.apiurl + "question/isAnswer", res => {
        if (res && res.answerId) {
          this.$routerGo(this, "replace", {
            path: "/homePage/qa/answerLord"
          });
        } else {
          this.isShowInvite = true;
        }
      });
    },
    //获取验证码
    getVCode: function () {
      if (isClicking) {
        return;
      }
      if (utilJs.isPhoneNumber(this.userPhone)) {
        if (this.imgCode == '') {
          this.$showCjToast({
            text: "图片验证码不能为空",
            type: "warn",
          });
        } else {
          isClicking = true;
          let $this = this;
          // $this.vCodeTime--;
          utilJs.getMethod(`${global.apiurl}question/sendCode?mobile=${this.userPhone}&captcha=${this.imgCode}&captchaKey=${this.codeImgInfo.key}`,
            res => {
              isClicking = false;
              if (res.errMsg) {
                $this.vCodeTime = 60;
                this.$showCjToast({
                  text: res.errMsg,
                  type: "warn",
                });
              } else {
                vCodeTimeCon = setInterval($this.getYzMethod, 1000);
              }
            },
            isClicking = false,
            function () {
              clearInterval(vCodeTimeCon);
              $this.vCodeTime = 60;
              isClicking = false;
            }
          )
        }
      } else {
        this.$showCjToast({
          text: "请输入正确的手机号",
          type: "warn",
        });
      }
    },

    //验证码倒计时
    getYzMethod: function () {
      this.vCodeTime--;
      if (this.vCodeTime == 0) {
        clearInterval(vCodeTimeCon);
        this.vCodeTime = 60;
      }
    },
    //删除图片
    delUploadImage() {
      this.headUrl = "";
    },
    //选择图片
    clickChoosePic(event) {
      if (this.isWeiXin) {
        wxUtilJs.chooseImage().then(localIds => {
          wxUtilJs
            .uploadImage({ localId: localIds[0] })
            .then(serverId => {
              this.syncUploadPic(serverId);
            })
            .catch(function (err) {
              console.log(err);
            });
        });
      } else {
        utilJs.imgUpload(event.target.files, imgData, 'inviteLord', res => {
          this.headUrl = res;
        }, fRes => {});
      }
    },
    //上传图片到服务器
    syncUploadPic(serverId) {
      let serverIdArr = [];
      serverIdArr.push(serverId);

      utilJs.postMethod(
        global.apiurl + "question/downWxMedia",
        {
          serverId: JSON.stringify(serverIdArr),
          mediaType: 2
        },
        res => {
          if (res.length > 0) {
            this.headUrl = res[0];
          }
        }
      );
    },

    //点击图片放大预览
    clickPreviewImage() {
      if (!this.headUrl) {
        return;
      }
      let imgUrlList = [];
      imgUrlList.push(this.headUrl);
      wxUtilJs.previewImage({
        current: this.headUrl, // 当前显示图片的http链接
        urls: imgUrlList // 需要预览的图片http链接列表
      });
    },
    //验证输入内容
    checkInput() {
       if (!this.userName || this.userName.length < 2) {
        this.$showCjToast({
          text: "请输入真实姓名",
          type: "warn",
        });
        return false;
      } else if (!utilJs.isPhoneNumber(this.userPhone)) {
        this.$showCjToast({
          text: "请输入正确的手机号",
          type: "warn",
        });
        return false;
      } else if (!this.vCode) {
        this.$showCjToast({
          text: "请输入验证码",
          type: "warn",
        });
        return false;
      } else if (!this.headUrl) {
        this.$showCjToast({
          text: "请上传真实头像",
          type: "warn",
        });
        return false;
      } else if (this.questionCustom == 1) {
        if (this.honor == '') {
          this.$showCjToast({
            text: "请输入光之管道等级",
            type: "warn",
          });
          return false;
        } else if (this.price == '') {
          this.$showCjToast({
            text: "光之管道收费价格",
            type: "warn",
          });
          return false;
        } else if (!!this.price) {
          let priceReg = /(^\d{1,5}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
          if (!priceReg.test(this.price)) {
            if (this.price < 100000) {
              this.$showCjToast({
                text: "请输入正确价格",
                type: "warn",
              });
              return false;
            } else {
              this.$showCjToast({
                text: "小于10万",
                type: "warn",
              });
              return false;
            }
          } else {
            return true;
          }
        } else {
          return true;
        }
      } else {
        return true;
      }
    },

    //点击接受邀请
    clickAccessInvite() {
      if (!this.checkInput()) {
        return;
      }
      if (isClicking) {
        return;
      }
      let that = this;
      isClicking = true;
      utilJs.postMethod(
        global.apiurl + "question/registerAnswer",
        {
          name: this.userName,
          mobile: this.userPhone,
          code: this.vCode,
          avatar: this.headUrl,
          lecturerId: this.lecturerId,
          honor: this.honor,
          intro: this.intro,
          price: this.price,
          remark: this.remark,
        },
        res => {
          isClicking = false;
          this.$showCjToast({
            text: "注册成功",
            type: "success",
          }).then(() => {
            that.$routerGo(that, "push", {
              path: "/homePage/qa/applySuccess"
            });
          });
        },
        failRes => {
          isClicking = false;
        }
      );
    },
    //分享
    wechatShare: function () {
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/qa/inviteLord?lecturerId=${this.lecturerId}&refereeId=${localStorage.getItem("userId")}`;
      let title = this.questionCustom == 1 ? this.questionInfo.readerTitle : '';
      let shareImg = this.questionCustom == 1 ? this.questionInfo.cover : '';
      let shareDesc = this.questionCustom == 1 ? this.questionInfo.readerDescribe : '';
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare() {
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/qa/inviteLord?lecturerId=${this.lecturerId}&refereeId=${localStorage.getItem("userId")}`;
      let title = this.questionCustom == 1 ? this.questionInfo.readerTitle : '';
      let shareImg = this.questionCustom == 1 ? this.questionInfo.cover : '';
      let shareDesc = this.questionCustom == 1 ? this.questionInfo.readerDescribe : '';
      utilJs.appShareTrue(shareUrl, title, shareImg, shareDesc);
    }
  },
  activated() {
    if (this.questionCustom == 1) {
      setDocumentTitle("光之管道注册");// eslint-disable-line
    } else {
      setDocumentTitle("邀请答主");// eslint-disable-line
    }
    this.isWeiXin = utilJs.isWeiXin();
    this.lecturerId = this.$route.query.lecturerId || '';
    let companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
    if ((this.questionInfo && this.questionInfo.status == -1) || (companyAuth && companyAuth.enableQuestionModule == -1)) {
      this.$routerGo(this, "replace", {
        path: "/error/emptyPage",
        query: {
          info: "问答已下架"
        }
      });
      return;
    }
    this.isShowInvite = '';
    this.codeImgInfo = '';
    this.imgCode = '';
    this.honor = "",
    this.intro = "",
    this.price = "",
    this.remark = "",
    this.getImgCode();
    this.getSelfAnswerInfo();
    isClicking = false;
    this.$store.commit("updateLoadingStatus", {
      isLoading: false
    });
    //获取阿里云签名，除了微信浏览器以外
    if (!utilJs.isWeiXin()) {
      utilJs.getAliSign(`${global.apiurl}imageSign`, res => {
        imgData = res;
      });
    }
    this.wechatShare();
  },
  deactivated() { }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
input {
  border: none;
  background: none;
  outline: none;
}
.upload-img-del {
  cursor: pointer;
  position: absolute;
  right: -0.2rem;
  top: -0.2rem;
  font-size: 0.3rem;
  background-color: #d8d8d8;
  border-radius: 50%;
  width: 0.7rem;
  height: 0.7rem;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}
.modal-textarea {
  padding: 0.5rem 0.7rem 0.35rem 0.7rem;
  width: 100%;
  height: 4rem;
}
textarea {
  width: 100%;
  height: 2.3rem;
  border: none;
  outline: none;
  background: none;
}
.price {
  border-bottom: 1px solid #e5e5e5 !important;
}
</style>
